// pages/index/index.js
import { getUserLevel, DIFFICULTY_LEVELS, CHECKIN_REWARDS, getNextCheckinReward } from '../../utils/constants';
import { checkDailySignIn } from '../../utils/utils';

Page({
  data: {
    userInfo: null,
    hasUserInfo: false,
    canIUseGetUserProfile: false,
    bannerImages: [
      'https://game-1257928604.cos.ap-guangzhou.myqcloud.com/guess/level1/1.jpg',
      'https://game-1257928604.cos.ap-guangzhou.myqcloud.com/guess/level1/2.jpg',
      'https://game-1257928604.cos.ap-guangzhou.myqcloud.com/guess/level1/3.png'
    ],
    levelInfo: [
      { 
        name: '初级', 
        desc: '解锁一个个经典的成语故事。每一张图片都暗藏玄机，仔细观察，你就能发现其中的奥秘！', 
        color: '#10B981', 
        icon: '/assets/images/level_beginner.png', 
        type: DIFFICULTY_LEVELS.BEGINNER
      },
      { 
        name: '中级', 
        desc: '中级关卡将带你进入更丰富的成语世界，图片更复杂，成语更巧妙，快来接受挑战吧！', 
        color: '#F59E0B', 
        icon: '/assets/images/level_intermediate.png', 
        type: DIFFICULTY_LEVELS.INTERMEDIATE
      },
      { 
        name: '高级', 
        desc: '高级关卡将带你进入成语的深邃世界，图片暗藏玄机，成语寓意深远，只有真正的成语大师才能通关！', 
        color: '#EF4444', 
        icon: '/assets/images/level_advanced.png', 
        type: DIFFICULTY_LEVELS.ADVANCED
      }
    ],
    dailyTask: {
      completed: false,
      reward: 10 // 默认值，会在 onShow 中更新
    },
    showAuthDialog: false
  },

  onLoad: function () {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      });
    }
  },

  onShow: async function () {
    try {
      await this.initializeUserInfo();
    } catch (error) {
      console.error('初始化用户信息失败:', error);
      wx.showToast({
        title: '获取用户信息失败',
        icon: 'none'
      });
    }
  },

  /**
   * 初始化用户信息
   */
  async initializeUserInfo() {
    try {
      const app = getApp();
      
      // 等待登录完成
      await app.loginReady;
      
      // 获取用户信息
      const userInfo = await app.getUserInfo(app.globalData.userInfo.openId);
      // 获取用户等级信息
      const levelInfo = getUserLevel(userInfo.score || 0);
      userInfo.level = levelInfo.name;
      userInfo.levelClass = levelInfo.levelClass;
      userInfo.className = levelInfo.className;
      userInfo.avatarClass = levelInfo.avatarClass;
      
      this.setData({
        userInfo,
        hasUserInfo: true,
        dailyTask: {
          completed: checkDailySignIn(userInfo.lastCheckin),
          reward: getNextCheckinReward(userInfo.checkinDays || 0) // 根据签到天数获取下一次签到的奖励
        }
      });
      
      this.updateLevelInfo();
    } catch (error) {
      console.error('初始化用户信息失败:', error);
      wx.showToast({
        title: '获取用户信息失败',
        icon: 'none'
      });
    }
  },

  
  /**
   * 检查关卡是否解锁
   * @param {number} levelType 关卡类型
   * @returns {boolean} 是否解锁
   */
    isLevelUnlocked(levelType) {
    const progress = this.getAllLevelProgress();
    if (!progress) return false;

    switch (levelType) {
      case DIFFICULTY_LEVELS.BEGINNER:
        return true;
      case DIFFICULTY_LEVELS.INTERMEDIATE:
        return progress.beginner >= 5;
      case DIFFICULTY_LEVELS.ADVANCED:
        return progress.intermediate >= 5;
      default:
        return false;
    }
  },

  /**
   * 更新关卡信息
   */
  updateLevelInfo() {
    const levelInfo = this.data.levelInfo.map(level => {
      const progressInfo = this.getLevelProgress(level.type);
      return {
        ...level,
        unlocked: this.isLevelUnlocked(level.type,progressInfo),
        progress: progressInfo ? progressInfo.progress : 0,
        total: progressInfo ? progressInfo.total : 5
      };
    });

    this.setData({ levelInfo });
  },
  getAllLevelProgress() {
    if (!this.data.userInfo) return null;

    const completedLevels = this.data.userInfo.completedLevels || [];
    
    return {
      beginner: completedLevels.filter(level => level.startsWith('beginner_')).length,
      intermediate: completedLevels.filter(level => level.startsWith('intermediate_')).length,
      advanced: completedLevels.filter(level => level.startsWith('advanced_')).length
    };
  },
  /**
   * 获取关卡进度
   * @param {number} levelType 关卡类型
   * @returns {Object} 进度信息
   */
  getLevelProgress(levelType) {
    const progress = this.getAllLevelProgress();
    switch (levelType) {
      case DIFFICULTY_LEVELS.INTERMEDIATE:
        return {
          current: progress.beginner,
          required: 5,
          progress: progress.beginner,
          total: 5
        };
      case DIFFICULTY_LEVELS.ADVANCED:
        return {
          current: progress.intermediate,
          required: 5,
          progress: progress.intermediate,
          total: 5
        };
      default:
        return null;
    }
  },

  /**
   * 显示授权弹窗
   */
  showAuthPopup: function() {
    this.setData({
      showAuthDialog: true
    });
  },

  /**
   * 关闭授权弹窗
   */
  closeAuthPopup: function() {
    this.setData({
      showAuthDialog: false
    });
  },

  /**
   * 获取用户信息
   */
  getUserProfile: function () {
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        this.updateUserInfo(res.userInfo);
        this.setData({
          showAuthDialog: false
        });
        wx.showToast({
          title: '授权成功',
          icon: 'success'
        });
      },
      fail: (err) => {
        console.error('获取用户信息失败', err);
        wx.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 开始游戏
   */
  startGame: function(e) {
    const index = e.currentTarget.dataset.index;
    const level = this.data.levelInfo[index];
    
    if (!level.unlocked) {
      const requiredLevel = index === 1 ? '初级' : '中级';
      wx.showToast({
        title: `需要完成${requiredLevel}才能解锁`,
        icon: 'none'
      });
      return;
    }
    
    wx.navigateTo({
      url: `/pages/game/game?difficulty=${level.type}`
    });
  },

  /**
   * 页面跳转方法
   */
  navigateToLevelSelect: function () {
    wx.navigateTo({
      url: '/pages/level-select/level-select'
    });
  },

  navigateToDailyCheck: function () {
    wx.navigateTo({
      url: '/pages/daily-check/daily-check'
    });
  },

  navigateToUserCenter: function () {
    wx.switchTab({
      url: '/pages/user-center/user-center'
    });
  },

  navigateToRank: function () {
    wx.switchTab({
      url: '/pages/rank/rank'
    });
  }
});